#include "CCFile.h"

#include <boost/crc.hpp>

#include <sstream>

//TODO:refactor crc code

CCFile::CCFile( bfs::path fpath ):
	m_path(fpath)
	, m_filename( fpath.string() )
{
	std::ifstream ifs;
	std::filebuf * pbuf = 0;
	std::streamsize bufferSize;

	ifs.open(fpath.string().c_str(),std::ios::in );
	if( ifs.is_open() )
	{
			std::cout << "File opened.";
			pbuf = ifs.rdbuf();
			pbuf->pubseekpos(0);
			char * buffer = 0;	
			bufferSize = pbuf->pubseekoff( std::ios_base::beg, std::ios_base::end );
			pbuf->pubseekpos (0, std::ios::in);
			buffer=new char[bufferSize];
			pbuf->sgetn (buffer,bufferSize);			

			try
			{
				boost::crc_32_type crc;	
				crc.process_bytes( buffer, bufferSize );
				m_hash = crc.checksum();
				m_filePathHash = pathHash(m_path);
			}
			catch( std::exception& e )
			{
				std::cout << "exception occured in crc.." << e.what();
			}

			pbuf->close();
	}

	

	bfs::path absFOutDir = bfs::path(cacheDir() /= fileOutputPath() ).string();
	if( !bfs::exists( absFOutDir ) )
		bfs::create_directories( absFOutDir );
}

CCFile::~CCFile(void)
{
}

std::string CCFile::filePath()
{
	return m_filename;
}

std::size_t CCFile::filePathHash()
{	
	return m_filePathHash;	
}

std::size_t CCFile::crc()
{
	return m_hash;	
}

std::string CCFile::fileOutputPath()
{
	std::stringstream ss;
	ss << filePathHash() << nativeSeparator() << crc();
	return ss.str();
}
